package com.dzsw.filter;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;

import java.io.*;

public class RepeatedReadingRequestWrapper extends HttpServletRequestWrapper {

    private byte[] requestBodyBytes;

    private HttpServletRequest request;

    public RepeatedReadingRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.request = request;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (null == this.requestBodyBytes) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            StreamUtils.copy(request.getInputStream(), baos);
            this.requestBodyBytes = baos.toByteArray();
        }
        final ByteArrayInputStream bais = new ByteArrayInputStream(this.requestBodyBytes);

        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {
                throw new UnsupportedOperationException("Not supported");
            }

            @Override
            public int read() {
                return bais.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
